<template>
  <el-dialog
    v-el-drag-dialog
    :title="'已签收未回执订单详情'"
    :visible.sync="visible"
    width="1440px"
    @close="reset"
  >
    <div class="tableGroup">
      <lb-table
        ref="lbTable"
        v-loading="$loadingPlugin.fetchData"
        class="one"
        border
        highlight-current-row
        height="500"
        element-loading-text="加载中"
        :column="tableData.column"
        :data="tableData.data"
        pagination
        :total="tableData.total"
        custom-column
        @fetch="fetchData"
        @selection-change="handleSelectionChange"
        @row-click="toggleSelection"
        @select="selectTables"
        @select-all="selectAll"
      />
      <div style="margin: 20px 20px; font-weight: 700; color: #333;" />
      <lb-table
        ref="goodsTable"
        border
        class="two"
        min-height="200"
        highlight-current-row
        element-loading-text="加载中"
        :column="goodsTable.column"
        :data="goodsTable.data"
      />
    </div>
    <!-- 线上 onLine  月结支付 yj 预付支付：csmcard 现金支付：money 应totalMoney1   实totalMoney2 -->
    <div class="goodsTips">
      <span> 线上支付： {{ onLine }} </span>
      <span> 月结支付： {{ yj }} </span>
      <span> 预付支付： {{ csmcard }} </span>
      <span> 现金支付： {{ money }} </span>
      <span> 总应收： {{ totalMoney1 }} </span>
      <span> 总实收： {{ totalMoney2 }} </span>
    </div>
    <div slot="footer" class="dialog-footer">
      <span v-if="csmCardOrderCode" id="order_newReceipt_sign_showCsmcardOrderCodeDiv" style="float: left; margin-left: 20px; font-size: 16px; color: red;">{{ csmCardOrderCode }}订单支付状态为预支付,请注意核对</span>
      <el-button @click="reset">
        关闭
      </el-button>
      <el-button :loading="$loadingPlugin.success " type="primary" @click="success">
        确认回执
      </el-button>
    </div>
  </el-dialog>
</template>

<script>
  import { orderbillNewReceiptDetailed, orderbillNewReceiptOrderDetail, orderbillNewReceiptOrderDetails, orderbillNewReceiptBatchReceipt } from '@/api'
  import { parseTime, formatColumnMap } from '@/utils'
  // import tableData from './data.json'
  export default {
    name: 'dispose',
    props: ['payStatusMap', 'paymentMethodMap'],
    data() {
      return {
        visible: false,
        // 线上 onLine  月结支付 yj 预付支付：csmcard 现金支付：money 应totalMoney1   实totalMoney2
        onLine: 0,
        yj: 0,
        csmcard: 0,
        money: 0,
        totalMoney1: 0,
        totalMoney2: 0,
        csmCardOrderCode: null,
        searchParams: {},
        selectTable: [],
        tableData: {
          total: 0,
          column: [
            {
              type: 'index',
              prop: '',
              align: 'center',
              fixed: true
            },
            {
              type: 'selection',
              align: 'center',
              fixed: true
            },
            {
              prop: 'signDt',
              label: '签收日期',
              width: 110,
              render: (h, { row }) => <span>{ row.signDt && parseTime(row.signDt, '{y}-{m}-{d}') }</span>
            },
            {
              prop: 'orderCode',
              label: '订单号',
              showOverflowTooltip: true
            },
            {
              prop: 'transactTime',
              label: '下单日期',
              width: 160,
              render: (h, { row }) => <span>{ row.transactTime && parseTime(row.transactTime, '{y}-{m}-{d} {h}:{i}:{s}') }</span>
            },
            {
              prop: 'signTime',
              label: '签收时间',
              width: 160,
              showOverflowTooltip: true,
              render: (h, { row }) => <span>{ row.signDt && parseTime(row.signDt, '{y}-{m}-{d} {h}:{i}:{s}') }</span>
            },
            {
              prop: 'csmCode',
              label: '客户编号'
            },
            {
              prop: 'csmName',
              label: '客户名称'
            },
            {
              prop: 'contactPhone',
              label: '联系电话',
              width: 110
            },
            {
              prop: 'goodsDesc',
              label: '商品描述',
              showOverflowTooltip: true,
              width: 180
            },
            {
              prop: 'treceivables',
              label: '应收金额',
              width: 110
            },
            {
              prop: 'taccReceivable',
              label: '实收金额'
            },
            {
              prop: 'ownerName',
              label: '配送员',
              width: 100
            },
            {
              prop: 'paymentMethod',
              label: '支付方式',
              render: (h, { row }) => <span>{ row.paymentMethod && formatColumnMap(this.paymentMethodMap, 'value', row.paymentMethod, 'desc') }</span>
            },
            {
              prop: 'payStatus',
              label: '支付状态',
              render: (h, { row }) => <span>{ row.payStatus && formatColumnMap(this.payStatusMap, 'value', row.payStatus, 'desc') }</span>
            }

          ],
          data: []
        },
        goodsTable: {
          total: 0,
          column: [
            {
              type: 'index',
              prop: '',
              align: 'center',
              label: ''
            },
            {
              prop: 'goodsName',
              label: '商品名称'
            },
            {
              prop: 'specName',
              label: '规格型号',
              showOverflowTooltip: true
            },
            {
              prop: 'unitName',
              label: '单位'
            },
            {
              prop: 'count',
              label: '数量'
            },
            {
              prop: 'sendWeight',
              label: '送出重量'
            },
            {
              prop: 'fee3',
              label: '收回重量'
            }
          ],
          data: []
        }
      }
    },
    methods: {
      async fetchData({ currentPage = 1, pageSize = 20 }) {
        const params = {
          ...this.searchParams,
          currentPage,
          pageSize
        }

        const res = await orderbillNewReceiptDetailed(params)
        this.tableData.data = res.data.rows
        if (currentPage === 1) this.tableData.total = res.data.total
        // this.flexColumnWidth()
      },
      open(row) {
        return new Promise(resolve => {
          this.resolve = resolve
          this.visible = true
          this.searchParams = { ...row }
          this.fetchData({})
        })
      },
      async success() {
        console.log(this.selectTable)
        if (!this.selectTable.length) {
          this.$message.error('请先选择订单')
          return
        }
        this.$confirm('确认回执？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async() => {
          var list = this.selectTable.map(l => l.orderCode)
          const params = {
            orderCodes: list.join(',')
          }
          const res = await orderbillNewReceiptBatchReceipt(params)
          if (res.success) {
            this.$message.success('回执成功')
            this.reset()
            this.$emit('refresh')
          }
        })
      },
      handleSelectionChange(val, value) {
        console.log(val)
        this.selectTable = val
      },
      toggleSelection(row) {
        if (this.selectTable.find(l => l === row)) {
          var type = -1
        } else {
          type = 1
        }
        this.$nextTick(() => {
          this.$refs.lbTable.toggleRowSelection(row)
          this.selectOrderDetail(row, type)
        })
      },
      selectTables(selection, row) {
        console.log(selection, row)
        // this.$refs.lbTable.toggleRowSelection(row)
        if (this.selectTable.find(l => l === row)) {
          var type = -1
        } else {
          type = 1
        }
        this.$nextTick(() => {
          this.selectOrderDetail(row, type)
        })
      },
      selectAll(selection) {
        console.log(selection)
        var type
        if (selection.length) {
          type = 1
        } else {
          type = -1
        }
        this.selectAllOrderDetail(type)
      },
      toDecimal(str, p) {
        var reg = /^(-?\d+)(\.\d+)?$/
        if (reg.test(str)) {
          return parseFloat(str).toFixed(p || 2) * 1
        }
        return 0
      },
      isLinePay(pm) {
        return ((pm & 2) > 0 || (pm & 64) > 0 || (pm & 128) > 0 || (pm & 512) > 0 || (pm & 1024) > 0)
      },
      // 全选 /全取消
      async  selectAllOrderDetail(type) {
        // var this = this
        this.goodsTable.data = []
        this.onLine = 0
        this.yj = 0
        this.csmcard = 0
        this.money = 0
        this.totalMoney1 = 0
        this.totalMoney2 = 0
        this.csmCardOrderCode = 0
        if (type === 1) {
          // 获取所有订单号
          var orderCodes = ''
          var rows = this.tableData.data
          for (var x = 0; x < rows.length; x++) {
            orderCodes = orderCodes + rows[x].orderCode + ','
          }

          orderCodes = orderCodes.substr(0, orderCodes.length - 1)
          const rlt = await orderbillNewReceiptOrderDetails({ orderCodes: orderCodes })
          if (rlt.exc != null) {
            this.$message.error('查询异常\t' + rlt.exc); return
          } else if (!rlt.data) {
            this.$message.error('没有查询到相关数据'); return
          }
          // 检查table2中是否有当前是商品
          var goodsDetailList = rlt.data
          for (x = 0; x < goodsDetailList.length; x++) {
            var goodsDetailInfo = goodsDetailList[x]
            var table2Rows = this.goodsTable.data
            if (table2Rows.length > 0) {
              var isExistGoods = false // 不存在
              for (var y = 0; y < table2Rows.length; y++) {
                var table2Row = table2Rows[y]
                if (table2Row.goodsId === goodsDetailInfo.goodsId) {
                  isExistGoods = true
                  table2Row.goodsId = goodsDetailInfo.goodsId
                  table2Row.goodsName = goodsDetailInfo.goodsName
                  table2Row.count = Number(table2Row.count) + Number(goodsDetailInfo.gcount)
                  var fee3 = this.toDecimal(table2Row.fee3, 2) + this.toDecimal(goodsDetailInfo.fee3, 2)
                  table2Row.fee3 = this.toDecimal(fee3, 2).toFixed(2)
                  var sendWeight = this.toDecimal(table2Row.sendWeight, 2) + this.toDecimal(goodsDetailInfo.fee3, 2) + this.toDecimal(goodsDetailInfo.netWeight, 2)
                  table2Row.sendWeight = this.toDecimal(sendWeight, 2).toFixed(2)
                }
              }

              if (!isExistGoods) {
                // 追加数据到表格
                // goodsDetailInfo.goodsId = goodsDetailInfo.goodsId
                // goodsDetailInfo.goodsName = goodsDetailInfo.goodsName
                goodsDetailInfo.count = this.toDecimal(goodsDetailInfo.gcount, 0)
                goodsDetailInfo.fee3 = this.toDecimal(goodsDetailInfo.fee3, 2).toFixed(2)
                sendWeight = this.toDecimal(goodsDetailInfo.fee3, 2) + this.toDecimal(goodsDetailInfo.netWeight, 2)
                goodsDetailInfo.sendWeight = this.toDecimal(sendWeight, 2).toFixed(2)
                this.goodsTable.data.push(goodsDetailInfo)
              }
            } else {
              // 追加数据到表格
              // goodsDetailInfo.goodsId = goodsDetailInfo.goodsId
              // goodsDetailInfo.goodsName = goodsDetailInfo.goodsName
              goodsDetailInfo.count = this.toDecimal(goodsDetailInfo.gcount, 0)
              goodsDetailInfo.fee3 = this.toDecimal(goodsDetailInfo.fee3, 2).toFixed(2)
              sendWeight = this.toDecimal(goodsDetailInfo.fee3, 2) + this.toDecimal(goodsDetailInfo.netWeight, 2)
              goodsDetailInfo.sendWeight = this.toDecimal(sendWeight, 2).toFixed(2)
              this.goodsTable.data.push(goodsDetailInfo)
            }
          }

          rows = this.tableData.data
          for (x = 0; x < rows.length; x++) {
            var rowData = rows[x]
            // 计算线上支付 月结支付 预付支付 现金支付
            if (rowData.paymentMethod === 256 || rowData.paymentMethod === 4) { // 预付支付=气票+预付款
              // 计算预支付金额
              var csmcardMoney = this.toDecimal(this.csmcard, 2) + this.toDecimal(rowData.taccReceivable, 2) // 订单实收金额
              this.csmcard = (this.toDecimal(csmcardMoney, 2).toFixed(2))
            } else if (rowData.paymentMethod === 16) { // 月结
              var yjText = this.toDecimal(this.yj, 2) + this.toDecimal(rowData.taccReceivable, 2)
              this.yj = (this.toDecimal(yjText, 2).toFixed(2))
            } else if (rowData.paymentMethod === 1) { // 现金
              var moneyText = this.toDecimal(this.money, 2) + this.toDecimal(rowData.taccReceivable, 2)
              this.money = (this.toDecimal(moneyText, 2).toFixed(2))
            } else { // 线上支付
              if (this.isLinePay(rowData.paymentMethod)) {
                var onLineText = this.toDecimal(this.onLine, 2) + this.toDecimal(rowData.taccReceivable, 2)
                this.onLine = (this.toDecimal(onLineText, 2).toFixed(2))
              }
            }
            var titalMoney1Text = this.toDecimal(this.totalMoney1, 2) + this.toDecimal(rowData.treceivables, 2)
            // 总应收
            this.totalMoney1 = (this.toDecimal(titalMoney1Text, 2).toFixed(2))
            var titalMoney2Text = this.toDecimal(this.totalMoney2, 2) + this.toDecimal(rowData.taccReceivable, 2)
            // 总实收
            this.totalMoney2 = (this.toDecimal(titalMoney2Text, 2).toFixed(2))

            if (rowData.payStatus === 2) { // 说明是预支付
              this.csmCardOrderCode = (rowData.orderCode) // 预支付订单号
              this.showCsmcardOrderCodeDiv.show() // 显示预支付订单号
            }
          }
        }
      },
      // 根据订单号查询商品 添加或减少商品
      async selectOrderDetail(rowData, type) {
        const params = {
          orderCode: rowData.orderCode
        }
        const rlt = await orderbillNewReceiptOrderDetail(params)
        if (rlt.exc != null) {
          this.$message.error('查询异常\t' + rlt.exc); return
        } else if (!rlt.data) {
          this.$message.error('没有查询到相关数据'); return
        }

        // 检查table2中是否有当前是商品
        var goodsDetailList = rlt.data
        var rows = this.goodsTable.data
        // var goodsCount = 1
        if (rows.length > 0) {
          for (var x = 0; x < goodsDetailList.length; x++) {
            var goodsId = goodsDetailList[x].goodsId
            var isExistGoods = false // 不存在
            for (var y = 0; y < rows.length; y++) {
              if (rows[y].goodsId === goodsId) { // 说明存在当前商品
                isExistGoods = true// 说明存在商品
                if (type === 1) { // 说明是追加
                  rows[y].goodsId = goodsDetailList[x].goodsId
                  rows[y].goodsName = goodsDetailList[x].goodsName
                  rows[y].count = Number(rows[y].count) + Number(goodsDetailList[x].gcount)

                  var fees = this.toDecimal(rows[y].fee3, 2) + this.toDecimal(goodsDetailList[x].fee3, 2)
                  rows[y].fee3 = this.toDecimal(fees, 2).toFixed(2)

                  var sendWeight = this.toDecimal(rows[y].sendWeight, 2) + this.toDecimal(goodsDetailList[x].fee3, 2) + this.toDecimal(goodsDetailList[x].netWeight, 2)
                  rows[y].sendWeight = this.toDecimal(sendWeight, 2).toFixed(2)
                } else if (type === -1) { // 说明是取消勾选
                  rows[y].goodsId = goodsDetailList[x].goodsId
                  rows[y].goodsName = goodsDetailList[x].goodsName
                  rows[y].count = Number(rows[y].count) - Number(goodsDetailList[x].gcount)
                  var fee3 = this.toDecimal(rows[y].fee3, 2) - this.toDecimal(goodsDetailList[x].fee3, 2)
                  rows[y].fee3 = this.toDecimal(fee3, 2).toFixed(2)

                  var sendWeigth = this.toDecimal(rows[y].sendWeight, 2) - this.toDecimal(goodsDetailList[x].fee3, 2) - this.toDecimal(goodsDetailList[x].netWeight, 2)
                  rows[y].sendWeight = this.toDecimal(sendWeigth, 2).toFixed(2)
                }
                // 刷新单行表格数据
              }
            }

            if (!isExistGoods) { // 说明table2表格中不存在当前商品
              var goodsDetailInfo = goodsDetailList[x]
              // goodsDetailInfo.goodsId = goodsDetailInfo.goodsId
              // goodsDetailInfo.goodsName = goodsDetailInfo.goodsName
              goodsDetailInfo.count = Number(goodsDetailInfo.gcount)
              goodsDetailInfo.fee3 = this.toDecimal(goodsDetailInfo.fee3, 2).toFixed(2)
              sendWeight = this.toDecimal(goodsDetailInfo.fee3, 2) + this.toDecimal(goodsDetailInfo.netWeight, 2)
              goodsDetailInfo.sendWeight = this.toDecimal(sendWeight, 2).toFixed(2)
              this.goodsTable.data.push(goodsDetailInfo)
            }
          }
        } else {
          for (x = 0; x < goodsDetailList.length; x++) {
            goodsDetailInfo = goodsDetailList[x]
            // 追加数据到表格
            // goodsDetailInfo.goodsId = goodsDetailInfo.goodsId
            // goodsDetailInfo.goodsName = goodsDetailInfo.goodsName
            goodsDetailInfo.count = this.toDecimal(goodsDetailInfo.gcount, 0)
            goodsDetailInfo.fee3 = this.toDecimal(goodsDetailInfo.fee3, 2).toFixed(2)

            sendWeight = this.toDecimal(goodsDetailInfo.fee3, 2) + this.toDecimal(goodsDetailInfo.netWeight, 2)
            goodsDetailInfo.sendWeight = this.toDecimal(sendWeight, 2)

            this.goodsTable.data.push(goodsDetailInfo)
          }
        }
        if (type === 1) {
          // 线上 onLine  月结支付 yj 预付支付：csmcard 现金支付：money 应totalMoney1   实totalMoney2
          // 计算线上支付 月结支付 预付支付 现金支付
          if (rowData.paymentMethod === 256 || rowData.paymentMethod === 4) { // 预付支付=气票+预付款
            // 计算预支付金额
            var csmcardMoney = this.toDecimal(this.csmcard, 2) + this.toDecimal(rowData.taccReceivable, 2) // 订单实收金额
            this.csmcard = (this.toDecimal(csmcardMoney, 2).toFixed(2))
          } else if (rowData.paymentMethod === 16) { // 月结
            var yjText = this.toDecimal(this.yj, 2) + this.toDecimal(rowData.taccReceivable, 2)
            this.yj = (this.toDecimal(yjText, 2).toFixed(2))
          } else if (rowData.paymentMethod === 1) { // 现金
            var moneyText = this.toDecimal(this.money, 2) + this.toDecimal(rowData.taccReceivable, 2)
            this.money = (this.toDecimal(moneyText, 2).toFixed(2))
          } else { // 线上支付
            if (this.isLinePay(rowData.paymentMethod)) {
              var onLineText = this.toDecimal(this.onLine, 2) + this.toDecimal(rowData.taccReceivable, 2)
              this.onLine = (this.toDecimal(onLineText, 2).toFixed(2))
            }
          }
          var titalMoney1Text = this.toDecimal(this.totalMoney1, 2) + this.toDecimal(rowData.treceivables, 2)
          // 总应收
          this.totalMoney1 = (this.toDecimal(titalMoney1Text, 2).toFixed(2))
          var titalMoney2Text = this.toDecimal(this.totalMoney2, 2) + this.toDecimal(rowData.taccReceivable, 2)
          // 总实收
          this.totalMoney2 = (this.toDecimal(titalMoney2Text, 2).toFixed(2))

          if (rowData.payStatus === 2) { // 说明是预支付
            this.csmCardOrderCode = (rowData.orderCode) // 预支付订单号
            this.showCsmcardOrderCodeDiv.show() // 显示预支付订单号
          }
        } else if (type === -1) {
          // 计算线上支付 月结支付 预付支付 现金支付
          if (rowData.paymentMethod === 256 || rowData.paymentMethod === 4) { // 预付支付=气票+预付款
            // 计算预支付金额
            csmcardMoney = this.toDecimal(this.csmcard, 2) - this.toDecimal(rowData.taccReceivable, 2) // 订单实收金额
            this.csmcard = (this.toDecimal(csmcardMoney, 2).toFixed(2))
          }
          if (rowData.paymentMethod === 16) { // 月结
            yjText = this.toDecimal(this.yj, 2) - this.toDecimal(rowData.taccReceivable, 2)
            this.yj = (this.toDecimal(yjText, 2).toFixed(2))
          } else if (rowData.paymentMethod === 1) { // 现金
            moneyText = this.toDecimal(this.money, 2) - this.toDecimal(rowData.taccReceivable, 2)
            this.money = (this.toDecimal(moneyText, 2).toFixed(2))
          } else { // 线上支付
            if (this.isLinePay(rowData.paymentMethod)) {
              onLineText = this.toDecimal(this.onLine, 2) - this.toDecimal(rowData.taccReceivable, 2)
              this.onLine = (this.toDecimal(onLineText, 2).toFixed(2))
            }
          }
          titalMoney1Text = this.toDecimal(this.totalMoney1, 2) - this.toDecimal(rowData.treceivables, 2)
          // 总应收
          this.totalMoney1 = (this.toDecimal(titalMoney1Text, 2).toFixed(2))
          titalMoney2Text = this.toDecimal(this.totalMoney2, 2) - this.toDecimal(rowData.taccReceivable, 2)
          // 总实收
          this.totalMoney2 = (this.toDecimal(titalMoney2Text, 2).toFixed(2))

          if (rowData.payStatus === 2) { // 说明是预支付
            this.csmCardOrderCode = (rowData.orderCode) // 预支付订单号
            this.showCsmcardOrderCodeDiv.hide() // 显示预支付订单号
          }
        }
      },
      reset() {
        this.$nextTick(() => {
          this.goodsTable.data = []
          this.tableData.data = []
          this.onLine = 0
          this.yj = 0
          this.csmcard = 0
          this.money = 0
          this.totalMoney1 = 0
          this.totalMoney2 = 0
          this.csmCardOrderCode = 0
          this.visible = false
        })
      }
    }

  }
</script>

<style lang="scss" scoped>
.goodsTips {
  margin-top: 20px;
  font-family: Microsoft YaHei, Microsoft YaHei-Regular;
  font-size: 14px;
  font-weight: 400;
  line-height: 24px;
  color: #f24024;
  text-align: left;
  span {
    margin-right: 5px;
  }
}
.tableGroup {
  display: flex;
  height: 500px;
  .one {
    width: 65%;
  }
}
</style>
